//koa  koa-router koa-static koa-bodyparser

const Koa =require('koa');

const app = new Koa();

//async await  app.use();

let static = require('koa-static');

const path = require('path');

const router = require('koa-router')();

const query = require('./db/index');

const bodyparser = require('koa-bodyparser');

//挂在处理静态资源的中间件
app.use(static(path.join(__dirname,'./public/')));

app.use(bodyparser());

//挂载路由

app.use(router.routes());

app.use(router.allowedMethods());

//查询  分页
router.get('/api/list',async ctx => {
    let data = await query('select * from bloglist');
    ctx.body = {
        code:1,
        data
    }
})

//添加
router.post('/api/add',async ctx => {
    let time = new Date();
    let {username,title,con} = ctx.request.body;
    //容错处理
    if(username && title && con){
        try{
            await query('insert into bloglist (username,title,con,time) values (?,?,?,?)',[username,title,con,time]);
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }   
    }else{
        ctx.body = {
            code:0,
            msg:'参数有误'
        }
    }
})

//修改
router.put('/api/update',async ctx => {
    let {title,con,id} = ctx.request.body;
    //容错处理
    if(title && con && id){
        try{
            await query('update bloglist set title=?,con=? where id=?',[title,con,id]);
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }   
    }else{
        ctx.body = {
            code:0,
            msg:'参数有误'
        }
    }
})

router.delete('/api/del',async ctx => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from bloglist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:0,
            msg:'参数有误'
        }
    }
})

app.listen(3000,() => {
    console.log("====")
})